import React from 'react';
import { Form, Drawer, Collapse, Checkbox, Descriptions, Button, Steps, Icon } from 'antd';
import { connect } from 'dva';

import styles from './index.less';
import StepOne from './step-one.js';
import StepTwo from './step-two.js';
import StepThree from './step-three.js';
import StepFour from './step-four.js';
import StepFive from './step-five.js';
import StepSix from './step-six.js';

import { administratorsSa } from '../../services/API';

const { Step } = Steps;
const { Panel } = Collapse;

const namespace = 'returnRoules';
// const FormItem = Form.Item;
// const CheckboxGroup = Checkbox.Group;
/**
 *  登录界面
 */
@connect(({ returnRoules }) => ({
  rulesList: returnRoules.rulesList,
  stepCurrent: returnRoules.stepCurrent,
  rouleId: returnRoules.rouleId,
  activeKey: returnRoules.activeKey,
  rulesDetail: returnRoules.rulesDetail,
  showDrawer: returnRoules.showDrawer
}))
@Form.create()
class RetunRoules extends React.Component {
  maxStep = 0;
  state = {
    editReturnRule: null,
    current: 0, //步骤
    showDrawer: false, //是否显示抽屉
    resetReturnFeeTips: {
      1: 'of good value',
      2: 'of good value + tax',
      3: 'of good value + tax +delivery fee'
    },
    damageCompensationTips: {
      1: 'of good value',
      2: 'of good value + tax',
      3: 'of good value + tax +delivery fee'
    }
  };
  componentDidUpdate() {
    if (this.props.stepCurrent > this.maxStep) {
      this.maxStep = this.props.stepCurrent;
    }
  }
  async componentDidMount() {
    let userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      const roleId = userInfo.roles[0].roleId;
      let resp = await administratorsSa();
      if (resp.code === 200) {
        const data = resp.data;
        for (let i = 0, ii; (ii = data[i++]); ) {
          if (ii.roleId === roleId) {
            this.setState({
              editReturnRule: ii.editReturnRule
            });
            return;
          }
        }
      }
    }
  }
  handleChangeSteps = e => {
    if (e > this.maxStep) {
      return;
    }
    if (e === 3) {
      this.props.dispatch({
        type: `${namespace}/getAllServiceProvider`
      });
    } else if (e === 4) {
      this.props.dispatch({
        type: `${namespace}/fetchRules`,
        payload: {
          id: this.props.rulesDetail.id
        }
      });
    }
    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        stepCurrent: e
      }
    });
  };
  // 关闭抽屉
  onClose = () => {
    if (this.closing) return;
    this.closing = true;
    this.props.dispatch({
      type: `${namespace}/fetchRules`,
      payload: {
        id: this.props.rouleId || this.props.rulesDetail.id
      },
      callback: res => {
        if (!res) {
          this.closing = false;
          return;
        }
        if (res.startDate) {
          this.props.dispatch({
            type: `${namespace}/save`,
            payload: {
              showDrawer: false,
              rulesDetail: null,
              stepCurrent: 0
            }
          });
          this.closing = false;
        } else {
          this.props.dispatch({
            type: `${namespace}/deleteRules`,
            payload: {
              returnRulesId: res.id
            },
            callback: () => {
              this.closing = false;
            }
          });
        }
      }
    });
  };
  // 开启抽屉
  handleShowDrawer = (e, num) => {
    e.stopPropagation();
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo) return;
    this.maxStep = 0;
    if (num >= 0) {
      this.props.dispatch({
        type: `${namespace}/save`,
        payload: {
          showDrawer: true,
          rulesDetail: this.props.rulesList[num],
          rouleId: this.props.rulesList[num].id,
          attachmentUrl: ''
        }
      });
      return;
    }
    // this.props.dispatch({
    //   type: `${namespace}/save`,
    //   payload: {
    //     stepCurrent: 0,
    //     showDrawer: true,
    //     activeKey: num
    //   }
    // });
    this.props.dispatch({
      type: `${namespace}/add`,
      payload: {
        // create: userInfo.nickName,
        shopsId: userInfo.shopId
      },
      callback: () => {
        this.props.dispatch({
          type: `${namespace}/save`,
          payload: {
            stepCurrent: 0,
            showDrawer: true,
            activeKey: num,
            attachmentUrl: ''
          }
        });
      }
    });
  };
  // 删除规则
  handleDelete(e, params) {
    e.stopPropagation();
    this.props.dispatch({
      type: `${namespace}/deleteRules`,
      payload: {
        returnRulesId: params.id
      }
    });
  }
  backStep() {
    if (this.props.stepCurrent === 0) return;
    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        stepCurrent: this.props.stepCurrent - 1
      }
    });
  }
  render() {
    const { rulesList, stepCurrent, showDrawer, activeKey = 0 } = this.props;
    let html = <StepOne></StepOne>;
    switch (stepCurrent) {
      case 1:
        html = <StepTwo></StepTwo>;
        break;
      case 2:
        html = <StepThree></StepThree>;
        break;
      case 3:
        html = <StepFour></StepFour>;
        break;
      case 4:
        html = <StepFive></StepFive>;
        break;
      case 5:
        html = <StepSix></StepSix>;
        break;
      default:
        html = <StepOne></StepOne>;
        break;
    }
    const { damageCompensationTips, resetReturnFeeTips, editReturnRule } = this.state;
    const plainOptions =
      rulesList.length > 0 && rulesList[activeKey].productsType && rulesList[activeKey].productsType.indexOf(',') > -1
        ? rulesList[activeKey].productsType.split(',').filter(a => a)
        : [];
    // console.log(rulesList, '规则列表');

    return (
      <div className={styles.retunRoules}>
        <h2>Return Rules</h2>
        <div className={styles.rulesbBtnList}>
          {editReturnRule ? (
            <Button className={styles.ruleBtn} type="primary" onClick={e => this.handleShowDrawer(e)}>
              Create new rules
            </Button>
          ) : null}
        </div>
        <div className={styles.rules}>
          <h3>Saved rules</h3>
          <div className={styles.list}>
            <Collapse
              bordered={false}
              accordion
              onChange={event => {
                this.props.dispatch({
                  type: `${namespace}/save`,
                  payload: {
                    activeKey: event ? event : activeKey
                  }
                });
              }}
            >
              {rulesList.filter(a => a.status !== null).length > 0 ? (
                rulesList
                  .filter(a => a.status !== null)
                  .map((item, index) => (
                    <Panel
                      key={index}
                      header={
                        <div className={styles.panelHeader}>
                          <h3 style={{ width: '100px', marginBottom: '4px' }}>Rule{index + 1}</h3>
                          <h3 className={styles.left}>Effective date:{item.startDate || 'dd-mm-yy'}</h3>
                          {item.status === 2 ? <div className={styles.tips}>Currently in use</div> : ''}
                          {item.status === 1 ? <div className={styles.tips}>Expired</div> : ''}
                          {item.status === 3 ? <div className={styles.tips}>Ready for use</div> : ''}
                          <div className={styles.right}>
                            {/* item.status === 3 &&  */}
                            {item.status === 3 ? (
                              <Button
                                icon="edit"
                                className={styles.ruleBtn}
                                type="primary"
                                onClick={e => this.handleShowDrawer(e, index)}
                              >
                                Edit
                              </Button>
                            ) : (
                              ''
                            )}
                            {/* item.status != 2 &&  */}
                            {item.status ? (
                              <Button
                                icon="delete"
                                className={styles.ruleBtn}
                                type="primary"
                                onClick={e => this.handleDelete(e, item)}
                              >
                                Delete
                              </Button>
                            ) : (
                              ''
                            )}
                          </div>
                        </div>
                      }
                    >
                      <div className={styles.panelContent}>
                        <div className={styles.ditem}>
                          <h3>Furnitrue type</h3>
                          <div className={styles.checkedList}>
                            <Checkbox.Group
                              disabled
                              options={
                                rulesList.length > 0 &&
                                rulesList[activeKey].productsType &&
                                rulesList[activeKey].productsType.indexOf(',') == -1
                                  ? [rulesList[activeKey].productsType]
                                  : plainOptions
                              }
                            />
                          </div>
                        </div>
                        <div className={styles.ditem}>
                          <div className={styles.item}>
                            <h3>Return days</h3>
                            <div className={styles.txt}>
                              {rulesList.length > 0 ? rulesList[activeKey].returnDays : ''} days
                            </div>
                          </div>
                          <div className={styles.item}>
                            <h3>packing</h3>
                            <div className={styles.txt}>
                              {rulesList.length > 0 ? rulesList[activeKey].originalPackingCharge : ''} days
                            </div>
                          </div>
                        </div>
                        <div className={styles.ditem}>
                          <div className={styles.ditemLeft}>
                            <h3>Accepted return Iocations</h3>
                            <div className={styles.list}>
                              {rulesList.length > 0 &&
                                rulesList[activeKey].returnLocation &&
                                rulesList[activeKey].returnLocation
                                  .split(',')
                                  .filter(a => a)
                                  .map(item => (
                                    <div key={item} className={styles.txt}>
                                      {item ? item.split('-')[0] : ''}
                                    </div>
                                  ))}
                            </div>
                          </div>
                          <div className={styles.ditemRight}>
                            <h3>Charged return Iocations</h3>
                            <div className={styles.list}>
                              {rulesList.length > 0 &&
                                rulesList[activeKey].particularAreas &&
                                rulesList[activeKey].particularAreas
                                  .split(',')
                                  .filter(a => a)
                                  .map(item => (
                                    <div key={item} className={styles.txt}>
                                      {item}
                                    </div>
                                  ))}
                            </div>
                          </div>
                        </div>
                        <div className={styles.locations}>
                          <Descriptions title="Accepted return locations">
                            <Descriptions.Item label="Is the original delivery fee refundable?">
                              {rulesList.length > 0 && rulesList[activeKey].originalShipping == 1 ? 'No' : 'Yes'}
                            </Descriptions.Item>
                            <Descriptions.Item label="Is the installation fee refundable?">
                              {rulesList.length > 0 && rulesList[activeKey].installation == 1 ? 'No' : 'Yes'}
                            </Descriptions.Item>
                            <Descriptions.Item label="Is the indoor delivery fee refundable?">
                              {rulesList.length > 0 && rulesList[activeKey].serviceFee == 1 ? 'No' : 'Yes'}
                            </Descriptions.Item>
                          </Descriptions>
                        </div>

                        <div className={styles.ditem}>
                          <h3>Packing fee</h3>
                          <div className={styles.test}>
                            {rulesList.length > 0 && rulesList[activeKey].packingCharge == 1
                              ? 'Per piece'
                              : 'Per order'}{' '}
                            - ${(rulesList.length > 0 && rulesList[activeKey].freight) || 0}
                          </div>
                        </div>
                        <Descriptions title="Additional service charge" column={1}>
                          {/* <Descriptions.Item label="White gloves service">${rulesList.length > 0 ? rulesList[activeKey].freight || 0 : '0'}</Descriptions.Item> */}
                          <Descriptions.Item label="Indoor pick-up">
                            $
                            {rulesList.length > 0
                              ? rulesList[activeKey].additionalCosts &&
                                rulesList[activeKey].additionalCosts.indexOf(',') > -1
                                ? rulesList[activeKey].additionalCosts.split(',')[0].split('-')[1]
                                : rulesList[activeKey].additionalCosts
                              : '0'}
                          </Descriptions.Item>
                          <Descriptions.Item label="Indoor pick-up and packing?">
                            $
                            {rulesList.length > 0
                              ? rulesList[activeKey].additionalCosts &&
                                rulesList[activeKey].additionalCosts.indexOf(',') > -1
                                ? rulesList[activeKey].additionalCosts.split(',')[1].split('-')[1]
                                : rulesList[activeKey].additionalCosts
                              : '0'}
                          </Descriptions.Item>
                        </Descriptions>
                        <Descriptions title="Payment" column={1}>
                          <Descriptions.Item label="Only orginal credit can be accepted?">
                            {rulesList.length > 0 && rulesList[activeKey].payType === 1 ? 'Yes' : 'No'}
                          </Descriptions.Item>
                        </Descriptions>
                        <Descriptions title="Restocking charges" column={1}>
                          <Descriptions.Item
                            label={
                              (rulesList.length > 0 &&
                              rulesList[activeKey].resetReturnFee &&
                              rulesList[activeKey].resetReturnFee.indexOf('-') > -1
                                ? rulesList[activeKey].resetReturnFee.split('-')[1]
                                : 0) + '%'
                            }
                          >
                            {(
                              rulesList.length > 0 &&
                              rulesList[activeKey].resetReturnFee &&
                              rulesList[activeKey].resetReturnFee.indexOf('-') > -1
                                ? rulesList[activeKey].resetReturnFee.split('-')[1]
                                : 0
                            )
                              ? resetReturnFeeTips[rulesList[activeKey].resetReturnFee.split('-')[0]]
                              : resetReturnFeeTips[1]}
                          </Descriptions.Item>
                        </Descriptions>
                        <Descriptions title="Damaged goods" column={1}>
                          <Descriptions.Item
                            label={
                              (rulesList.length > 0 &&
                              rulesList[activeKey].damageCompensation &&
                              rulesList[activeKey].damageCompensation.indexOf('-') > -1
                                ? rulesList[activeKey].damageCompensation.split('-')[1]
                                : 0) + '%'
                            }
                          >
                            {(
                              rulesList.length > 0 &&
                              rulesList[activeKey].damageCompensation &&
                              rulesList[activeKey].damageCompensation.indexOf('-') > -1
                                ? rulesList[activeKey].damageCompensation.split('-')[1]
                                : 0
                            )
                              ? damageCompensationTips[rulesList[activeKey].damageCompensation.split('-')[0]]
                              : damageCompensationTips[1]}
                          </Descriptions.Item>
                          {/* <Descriptions.Item label={(rulesList.length > 0 && rulesList[activeKey].damageCompensation && rulesList[activeKey].damageCompensation.indexOf('-') > -1 ? rulesList[activeKey].damageCompensation.split('-')[1] : 0) + '%'}>of good value</Descriptions.Item>
                        <Descriptions.Item label={(rulesList.length > 0 && rulesList[activeKey].damageCompensation && rulesList[activeKey].damageCompensation.indexOf('-') > -1 ? rulesList[activeKey].damageCompensation.split('-')[1] : 0) + '%'}>of good value + tax</Descriptions.Item>
                        <Descriptions.Item label={(rulesList.length > 0 && rulesList[activeKey].damageCompensation && rulesList[activeKey].damageCompensation.indexOf('-') > -1 ? rulesList[activeKey].damageCompensation.split('-')[1] : 0) + '%'}>of good value + tax +delivery fee</Descriptions.Item> */}
                        </Descriptions>
                        <div className={styles.ditem}>
                          <h3>Trucking service</h3>
                          <div className={styles.test}>The Return Company</div>
                        </div>
                      </div>
                    </Panel>
                  ))
              ) : (
                <div className={styles.noData}>No rules has been saved</div>
              )}
            </Collapse>
          </div>
        </div>
        <Drawer
          title="Return Rules"
          placement="right"
          destroyOnClose={true}
          closable={true}
          width="80%"
          onClose={this.onClose}
          visible={showDrawer}
        >
          <Steps current={stepCurrent} className={styles.steps} onChange={this.handleChangeSteps}>
            <Step
              title={
                <span>
                  Select non-returnable
                  <br />
                  products
                </span>
              }
            />
            <Step title="Return settings" />
            <Step title="Fee calculation" />
            <Step
              title={
                <span>
                  Set logistics service
                  <br />
                  providers
                </span>
              }
            />
            <Step title="Return policy" />
            <Step title="Effective date" />
          </Steps>
          <div className="formBox">
            <div className={[styles.backOper, stepCurrent === 0 ? styles.backDisable : {}].join(' ')}>
              <span
                onClick={() => {
                  this.backStep();
                }}
              >
                <Icon type="arrow-left" /> Back
              </span>
            </div>
            {html}
            <div
              className={[styles.backOper, stepCurrent === 0 ? styles.backDisable : {}].join(' ')}
              style={{ marginTop: 0 }}
            >
              <span
                onClick={() => {
                  this.backStep();
                }}
              >
                <Icon type="arrow-left" /> Back
              </span>
            </div>
          </div>
        </Drawer>
      </div>
    );
  }
}
export default RetunRoules;
